package com.servlet.user;

import com.entity.Code;
import com.entity.User;
import com.service.UserService;
import com.utils.JsonUtil;
import com.utils.TimeString;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

/**
 * 注册用户
 * 必选参数：username、password
 * 可选参数：email、description、tel
 */
@WebServlet(name = "register", value = "/register")
public class Register extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        JsonUtil jsonUtil = new JsonUtil();
        User user = new User();
        user.setUser_ip(jsonUtil.getIP(request));
        String name = request.getParameter("username");
        user.setUser_name(name);
        user.setUser_password(request.getParameter("password"));
        user.setUser_email(request.getParameter("email"));
        //头像
        user.setUser_description(request.getParameter("description"));
        user.setUser_tel(request.getParameter("tel"));
        user.setUser_create_time(new TimeString().TimeString());

        UserService userService = new UserService();
        try {
            User userName = userService.findUserName(name);
            if (userName!=null){
                Code code = new Code();
                code.setCode("403");
                code.setMsg("用户名已被占用，请换个用户名");
                String s = jsonUtil.JavaToJson(code);
                response.getWriter().print(s);
            }else {
                int i = userService.addUser(user);
                if (i==1){
                    Code code = new Code();
                    code.setCode("200");
                    code.setMsg("注册成功");
                    String s = jsonUtil.JavaToJson(code);
                    response.getWriter().print(s);
                }
//                else {
//                    Code code = new Code();
//                    code.setCode("403");
//                    code.setMsg("注册失败，请稍后再试");
//                    String s = jsonUtil.JavaToJson(code);
//                    response.getWriter().print(s);
//                }

            }
        }catch (Exception e){
            System.out.println("新增用户失败："+e+"\n--------------");
            Code code = new Code();
            code.setCode("403");
            code.setMsg("注册失败，请稍后再试");
            String s = jsonUtil.JavaToJson(code);
            response.getWriter().print(s);

        }

    }
}
